<!-- 课程预览页面 -->
<template>
  <view class="main">
    <uv-status-bar bgColor="#000"></uv-status-bar>
    <!--自定义头部 -->
    <view class="main-navbar">
      <zy-navbar></zy-navbar>
    </view>
    <view class="main-box">
      <view class="main-box-content" v-if="video" @touchstart="touchStart" @touchend="touchEnd">
        <!-- 如果当前视频地址是个图片，就直接展示一张图片 -->
        <template v-if="isFileType(video.address) === 'image'">
          <uv-image :src="video.address" height="100%" width="100%"></uv-image>
        </template>
        <!-- 如果当前地址是个视频，就播放视频 -->
        <template v-else-if="isFileType(video.address) === 'video'">
          <!-- <video class="main-box-video" :poster="video.cover" autoplay show-mute-btn enable-play-gesture :src="video.address"></video> -->
          <m-video
            class="main-box-video"
            autoplay
            loop
            show-speed-rate-btn
            show-casting-button
            show-mute-btn
            controls
            :src="video.address"
            :poster="video.cover"
            object-fit="cover"
            token="AsMqnVHVX5siSwwz4ckDCOCHCim5XsvNNXR1GkIVmrs="
          />
        </template>
        <!-- 如果当前地址是个音频 先展示封面-->
        <template v-else-if="isFileType(video.address) === 'mp3'">
          <view class="mp3-img">
            <uv-image :src="video.cover || defaultImagesList[random]" height="100%" width="100%"></uv-image>
          </view>
        </template>
        <!-- 如果当前视频地址是空，或者既不是视频，也不是图片 就只是展示个封面 -->
        <template v-else-if="!video.address || isFileType(video.address) === 'unknown'">
          <uv-image :src="video.cover || defaultImagesList[random]" height="100%" width="100%"></uv-image>
        </template>
      </view>
      <!-- <view class="main-box-shade"></view> -->
      <view class="main-box-info">
        <view class="left">
          <view class="main-box-info-title">
            <view class="avatar" @click="onGoTeacher(httpData.teacher.id)">
              <uv-avatar :src="httpData.teacher.profilePhoto || defaultImages[2]" size="96rpx" mode="aspectFill"></uv-avatar>
              <view class="add" v-if="httpData.teacher.collected && !httpData.teacher.collected.id" @click.stop="onCollect"> + </view>
            </view>
            <text class="name" :data-content="httpData.teacher.username">
              {{ httpData.teacher.username }}
            </text>
          </view>
          <view class="main-box-info-content">
            <view class="mb-3 content" :data-content="httpData.data.week ? '时间：' + httpData.data.week : '时间：无数据'">
              时间：{{ httpData.data.week || '无数据' }}
            </view>
            <view class="flex flex-y-center mb-3 content" :data-content="'舞蹈：' + httpData?.lesson?.name">
              舞蹈：{{ httpData?.lesson?.name }}
            </view>
            <view
              class="flex flex-y-center mb-3 content"
              :data-content="
                httpData.merchant?.id
                  ? '地址：' + httpData.merchant.headquater.name + ' (' + httpData.merchant.name + ')'
                  : httpData.lesson?.address
                  ? '地址：' + httpData.lesson?.address
                  : '地址：暂未获得'
              "
            >
              <template v-if="httpData.merchant?.id"> 地址：{{ httpData.merchant.headquater.name }} ({{ httpData.merchant.name }}) </template>
              <template v-else-if="httpData.lesson?.address"> 地址：{{ httpData.lesson?.address }} </template>
              <template v-else>地址：暂未获得</template>
            </view>
            <view class="mb-3 content" :data-content="httpData.lesson?.danceType ? '舞曲：' + httpData.lesson?.danceType : '舞曲：无'">
              舞曲：{{ httpData.lesson?.danceType || '无' }}
            </view>
          </view>
        </view>
        <view class="right">
          <view class="title" data-content="课程难度">课程难度</view>
          <view @click="showDialog">
            <f-progress-dashboard :percentage="getPercentage(httpData.lesson?.grade)"></f-progress-dashboard>
          </view>
        </view>
      </view>
      <view class="main-box-audio" v-if="video && isFileType(video.address) === 'mp3'">
        <uv-icon :name="audio.state ? 'pause' : 'play-right'" color="#fff" size="28" @click="onAudio"></uv-icon>
      </view>
    </view>
    <view v-if="percentage">
      <uv-line-progress :percentage="percentage"></uv-line-progress>
    </view>
    <view class="main-comment">
      <view class="flex-2">
        <view class="main-comment-btn" @click="onGoDetail">课程详情</view>
      </view>
      <view class="flex-1">
        <button open-type="share" class="reset-button main-comment-icon">
          <uv-icon name="fenxiang" custom-prefix="custom-icon" color="#fff" size="31rpx"></uv-icon>
        </button>
      </view>
      <view class="flex-1 flex just-cont-right">
        <view
          class="main-comment-collect"
          :class="httpData.data.collected && httpData.data.collected.id === 0 ? '' : 'collect-active'"
          @click.stop="httpCollect(item)"
        >
          {{ httpData.data.collected && httpData.data.collected.id === 0 ? '+收藏' : '已收藏' }}
        </view>
      </view>
      <view class="flex-1 flex just-cont-right">
        <view class="main-comment-collect" @click.stop="downloadFile"> 下载 </view>
      </view>
    </view>
    <uv-safe-bottom></uv-safe-bottom>
    <uv-toast ref="toastRef"></uv-toast>
    <f-dialog-card v-model="dialog"></f-dialog-card>
  </view>
</template>
<script setup>
  import { defaultAvatar, defaultImages, defaultImagesList } from '@/common/js/global.js';
  import { reactive, ref, computed } from 'vue';
  import { onLoad, onHide, onUnload } from '@dcloudio/uni-app';
  import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs.js';
  import weekday from '@/common/js/weekday.js';
  import { onHome, onLeft, isFileType, getPercentage, suiji } from '@/common/js/fn';
  dayjs.extend(weekday);
  let random = ref(0);
  const toastRef = ref();
  // 需要传递的参数
  let params = reactive({
    id: ''
  });
  let httpData = reactive({
    data: { lesson: {} },
    teacher: {},
    merchant: {}
  });
  // 视频数据
  let video = computed(() => {
    return httpData.data.video;
  });
  const dialog = ref(false);
  // 音频 默认开始
  let audio = ref({
    duration: 0,
    state: true,
    content: ''
  });

  const touchStartX = ref(0);
  const touchStartY = ref(0);

  // 远程请求课程详情
  let httpDetail = async () => {
    random.value = await suiji(0, defaultImagesList.length - 1);
    let data = await uni.$uv.http.post('app/lesson/detail', params);
    httpData.teacher = data.teacher;
    httpData.merchant = data.merchant;
    httpData.lesson = data.lesson;
    httpData.data = {
      ...data,
      week:
        data.issueDate && !isNaN(dayjs(data.issueDate))
          ? '周' + ['日', '一', '二', '三', '四', '五', '六'][dayjs(data.issueDate).weekday()] + ` ${data.timeDuration}`
          : data.issueDate
    };
    if (isFileType(video.value.address) === 'mp3') {
      let innerAudioContext = uni.createInnerAudioContext();
      innerAudioContext.autoplay = true;
      innerAudioContext.src = video.value.address;
      innerAudioContext.onCanplay(() => {
        setTimeout(() => {
          audio.value.duration = innerAudioContext.duration;
        });
      });
      audio.value.content = innerAudioContext;
    }
  };
  // 销毁音频事件
  let audioDestroy = () => {
    if (!audio.value.content) return;
    audio.value.content.pause();
  };
  // 音乐是否播放
  let onAudio = () => {
    if (!audio.value.content) return;
    audio.value.content[audio.value.state ? 'pause' : 'play']();
    audio.value.state = !audio.value.state;
  };
  onLoad(option => {
    params.id = Number(option.id);
    httpDetail();
  });
  // 到下级页面是消失事件
  onHide(() => {
    audioDestroy();
  });
  // 到主页就是销毁事件 二个都要调用销毁方法
  onUnload(() => {
    audioDestroy();
  });

  // 触摸开始
  const touchStart = e => {
    touchStartX.value = e.touches[0].clientX;
    touchStartY.value = e.touches[0].clientY;
  };

  // 触摸结束
  const touchEnd = e => {
    let deltaX = e.changedTouches[0].clientX - touchStartX.value;
    let deltaY = e.changedTouches[0].clientY - touchStartY.value;
    if (Math.abs(deltaX) > 50 && Math.abs(deltaX) > Math.abs(deltaY)) {
      if (deltaX >= 0) {
      } else {
      }
    } else if (Math.abs(deltaY) > 50 && Math.abs(deltaX) < Math.abs(deltaY)) {
      if (deltaY < 0) {
        // 上滑跳转到课程详情
        uni.$uv.route({
          url: '/pages/main/course',
          params: {
            id: params.id
          }
        });
      } else {
      }
    } else {
    }
  };

  const onGoDetail = () => {
    uni.$uv.route({
      url: '/pages/main/course',
      params: {
        id: params.id
      }
    });
  };
  // 下载视频
  let percentage = ref(0);
  let downloadFile = async () => {
    // 先检查有没有打开保存视频的功能
    uni.authorize({
      scope: 'scope.writePhotosAlbum',
      success() {
        // 如果已经是打开的，直接下载视频
        const downloadTask = uni.downloadFile({
          url: httpData.data.video.address,
          success: res => {
            // 下载成功之后保存视频
            uni.saveVideoToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                toastRef.value.show({
                  overlay: false,
                  message: `下载成功`,
                  type: 'success'
                });
              },
              fail: val => {}
            });
          },
          fail: val => {}
        });
        downloadTask.onProgressUpdate(res => {
          percentage.value = Number(res.progress);
          if (percentage.value < 20) {
            toastRef.value.show({
              overlay: false,
              message: `视频下载中`,
              type: 'info'
            });
          }
          if (percentage.value === 100) percentage.value = 0;
        });
      },
      fail: val => {
        toastRef.value.show({
          overlay: false,
          duration: 5000,
          message: `请在右上角 打开设置，开启添加到相册`,
          type: 'error'
        });
      }
    });
  };
  let httpCollect = async () => {
    await uni.$uv.http.post(`app/collect/${!httpData.data.collected.id ? 'add' : 'cancel'}`, {
      classify: 'Lesson', //收藏类型
      objid: httpData.data.id, //收藏对象的数据ID
      optype: 'collect' //操作类型
    });
    httpData.data.collected.id = httpData.data.collected.id ? 0 : 1;
    toastRef.value.show({
      overlay: false,
      message: `${httpData.data.collected.id ? '' : '取消'}收藏成功`,
      type: 'success'
    });
  };
  const onGoTeacher = id => {
    uni.$uv.route({
      url: '/pages/me/share',
      params: {
        id
      }
    });
  };
  const onCollect = async val => {
    await uni.$uv.http.post(`app/collect/add`, {
      classify: 'Teacher', //收藏类型
      objid: httpData.teacher.id, //收藏对象的数据ID
      optype: 'collect' //操作类型
    });
    httpData.teacher.collected.id = httpData.teacher.collected.id ? 0 : 1;
    toastRef.value.show({
      overlay: false,
      message: `收藏成功`,
      type: 'success'
    });
  };

  const showDialog = () => {
    dialog.value = true;
  };
</script>
<style scoped lang="scss">
  .dis-i-flex {
    display: inline-flex;
  }
  .flex-y-center {
    align-items: center;
  }
  .just-cont-right {
    justify-content: flex-end;
  }
  .flex-1 {
    flex: 1;
  }
  .flex-2 {
    flex: 2;
  }
  .mb-3 {
    margin-bottom: 5rpx;
  }
  .main {
    overflow: hidden;
    height: 100vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    &-navbar {
      margin-left: 23rpx;
    }
    .collect-active {
      background-color: #b1b1b1 !important;
    }
    &-box {
      flex: 1;
      width: 100%;
      position: relative;
      .mp3-img {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translate(-50%, 0);
        width: 605rpx;
        height: 952rpx;
      }
      &-content {
        overflow: hidden;
        height: 100%;
        width: 100%;
        background-color: #000000;
      }
      &-audio {
        width: 100%;
        padding: 0 20rpx;
        position: absolute;
        bottom: 20rpx;
        z-index: 999;
        color: #fff;
      }
      &-video {
        overflow: hidden;
        height: 100%;
        width: 100%;
      }
      &-shade {
        width: 100%;
        height: 832rpx;
        background-image: linear-gradient(to top, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0) 100%);
        position: absolute;
        bottom: 0;
      }
      &-info {
        width: 100%;
        display: flex;
        justify-content: space-between;
        position: absolute;
        bottom: 87rpx;
        z-index: 999;
        color: #fff;
        .left {
          margin-left: 26rpx;
        }
        .right {
          margin-right: 50rpx;
          display: flex;
          flex-direction: column;
          align-items: center;
          .title {
            height: 110rpx;
            display: flex;
            align-items: end;
            margin-bottom: 25rpx;
            font-size: 35rpx;
            font-weight: bold;
            color: #fff;
            position: relative;
            z-index: 0;
          }
          .title::after {
            height: 110rpx;
            display: flex;
            align-items: end;
            content: attr(data-content);
            -webkit-text-stroke: 14rpx #000;
            position: absolute;
            left: 0;
            top: 0;
            z-index: -1;
          }
        }
        &-title {
          display: flex;
          align-items: flex-end;
          margin-bottom: 25rpx;
          .avatar {
            position: relative;
            border: 8rpx solid #000;
            border-radius: 50%;
            .add {
              width: 37rpx;
              height: 37rpx;
              border-radius: 50%;
              background-color: #ff7a66;
              position: absolute;
              bottom: -8.5rpx;
              right: -8.5rpx;
              color: #fff;
              line-height: 37rpx;
              text-align: center;
              font-size: 45rpx;
            }
          }
          .name {
            font-size: 35rpx;
            font-weight: bold;
            color: #fff;
            margin-left: 1.0901rem /* 20px -> 1.0901rem */;
            position: relative;
            z-index: 0;
          }
          .name::after {
            content: attr(data-content);
            -webkit-text-stroke: 14rpx #000;
            position: absolute;
            left: 0;
            top: 0;
            z-index: -1;
          }
        }
        &-content {
          margin-left: 35rpx;
          .content {
            font-size: 28rpx;
            font-weight: bold;
            color: #fff;
            position: relative;
            z-index: 0;
          }
          .content::after {
            content: attr(data-content);
            -webkit-text-stroke: 14rpx #000;
            position: absolute;
            left: 0;
            top: 0;
            z-index: -1;
          }
        }
      }
    }
    &-comment {
      height: 4.3605rem /* 80px -> 4.3605rem */;
      width: 100%;
      background-color: #2e2e2e;
      color: #fff;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      box-sizing: border-box;
      &-btn {
        width: 267rpx;
        height: 85rpx;
        font-size: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: $dance-main-color;
        border-radius: 42rpx;
      }
      &-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 66rpx;
        height: 58rpx;
        border: 2rpx solid #fff;
        border-radius: 20rpx;
      }
      &-collect {
        background-color: $dance-main-color;
        width: 124rpx;
        height: 51rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 47rpx;
        font-size: 28rpx;
      }
    }
  }
</style>
